package auth

import (
	"context"
	"errors"
	"fmt"
	"usercenter/internal/model"
	"usercenter/internal/svc"
	"usercenter/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

var (
	ErrUserNotFound = errors.New("用户不存在")
)

type UserAuthLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserAuthLogic {
	return &UserAuthLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserAuthLogic) UserAuth(req *types.UserRegisterRequest) (*types.UserRegisterResponse, error) {
	// 1. 参数校验
	if req.Email == "" {
		return nil, errors.New("邮箱不能为空")
	}
	if len(req.Password) < 6 {
		return nil, errors.New("密码长度不能少于6位")
	}
	if req.Code == "" {
		return nil, errors.New("验证码不能为空")
	}

	// 2. 验证码验证（添加服务检查）
	if l.svcCtx.VerificationMgr == nil {
		l.Logger.Error("验证码服务未初始化")
		return nil, errors.New("系统服务异常")
	}

	valid, err := l.svcCtx.VerificationMgr.VerifyCode(req.Email, req.Code)
	if err != nil {
		l.Logger.Errorf("验证码验证失败: email=%s, error=%v", req.Email, err)
		return nil, fmt.Errorf("验证码验证失败: %v", err)
	}
	if !valid {
		return nil, errors.New("验证码无效或已过期")
	}

	existingUser, err := l.svcCtx.UserModel.FindByEmail(req.Email)
	if err != nil {
		logx.WithContext(l.ctx).Errorf("查询用户失败 email:%s error:%v", req.Email, err)
		return nil, errors.New("系统错误")
	}
	if existingUser != nil {
		return nil, errors.New("该邮箱已注册") // HTTP 409 Conflict更合适
	}

	// 4. 创建用户（添加详细日志）
	user := &model.User{
		Email:    req.Email,
		Password: req.Password,
	}

	if err := l.svcCtx.UserModel.Create(user); err != nil {
		l.Logger.Errorf("创建用户失败: email=%s, error=%v", req.Email, err)
		return nil, errors.New("注册失败，请稍后重试:" + err.Error())
	}

	go func() {
		// 创建新的context避免使用已取消的请求context
		ctx := context.Background()
		err := l.svcCtx.GorseClient.CreatUserGorse(ctx, int(user.ID))
		if err != nil {
			logx.Errorf("同步用户到Gorse失败: %v", err)
		}
	}()

	l.Logger.Infof("用户注册成功: email=%s, id=%d", user.Email, user.ID)

	return &types.UserRegisterResponse{
		Code:    200,
		Message: "注册成功",
	}, nil
}
